// WebSocket连接
let ws;
let roomId;
let playerRole;
let isConnected = false;

// 全局计时器
let timerInterval = null;

// 游戏状态
let gameState = {
    player: {
        level: 1,
        gold: 100,
        hand: [],
        battle: [],
        maxHandSize: 6,
        health: 30,
        availableCards: new Array(6).fill(0)
    },
    opponent: {
        level: 1,
        gold: 100,
        hand: [],
        battle: [],
        health: 30,
        availableCards: new Array(6).fill(0)
    },
    timer: 20,
    round: 1,
    isRoundEnd: false
};

// WebRTC视频播放相关
let rtcPeer = null;
let videoChannel = null;
let receivedChunks = [];

// 显示加载动画
function showLoading(message = '加载中...') {
    const loadingDiv = document.createElement('div');
    loadingDiv.id = 'loading-overlay';
    loadingDiv.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        z-index: 3000;
        animation: fadeIn 0.3s ease;
    `;
    
    loadingDiv.innerHTML = `
        <div style="
            width: 50px;
            height: 50px;
            border: 3px solid #00f7ff;
            border-top: 3px solid transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        "></div>
        <p style="color: #00f7ff; font-size: 1.2rem; text-shadow: 0 0 10px #00f7ff;">${message}</p>
    `;
    
    document.body.appendChild(loadingDiv);
}

// 隐藏加载动画
function hideLoading() {
    const loadingDiv = document.getElementById('loading-overlay');
    if (loadingDiv) {
        loadingDiv.style.animation = 'fadeOut 0.3s ease';
        setTimeout(() => {
            if (loadingDiv.parentNode) {
                loadingDiv.parentNode.removeChild(loadingDiv);
            }
        }, 300);
    }
}

// 改进的连接状态指示器
function updateConnectionStatus(status) {
    let statusElement = document.getElementById('connection-status');
    if (!statusElement) {
        statusElement = document.createElement('div');
        statusElement.id = 'connection-status';
        statusElement.style.cssText = `
            position: fixed;
            top: 10px;
            left: 10px;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
            z-index: 1000;
            transition: all 0.3s ease;
        `;
        document.body.appendChild(statusElement);
    }
    
    switch (status) {
        case 'connected':
            statusElement.textContent = '已连接';
            statusElement.style.background = 'linear-gradient(45deg, #44ff44, #00cc00)';
            statusElement.style.color = 'white';
            break;
        case 'connecting':
            statusElement.textContent = '连接中...';
            statusElement.style.background = 'linear-gradient(45deg, #ffff44, #cccc00)';
            statusElement.style.color = 'black';
            break;
        case 'disconnected':
            statusElement.textContent = '已断开';
            statusElement.style.background = 'linear-gradient(45deg, #ff4444, #cc0000)';
            statusElement.style.color = 'white';
            break;
    }
}

// 改进的连接到服务器功能
function connectToServer() {
    updateConnectionStatus('connecting');
    const serverUrl = `ws://${window.location.hostname}:3000`;
    ws = new WebSocket(serverUrl);
    
    ws.onopen = () => {
        console.log('Connected to server');
        isConnected = true;
        updateConnectionStatus('connected');
    };
    
    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log('[客户端] 收到消息:', JSON.stringify(data, null, 2));
        if (data.type === 'play-video') {
            console.log('[客户端] 收到 play-video 消息，调用 setupWebRTC');
            setupWebRTC();
        } else {
            handleServerMessage(data);
        }
    };
    
    ws.onclose = () => {
        console.log('Disconnected from server');
        isConnected = false;
        updateConnectionStatus('disconnected');
    };
    
    ws.onerror = () => {
        updateConnectionStatus('disconnected');
    };
}

// 改进的创建房间功能
function createRoom() {
    if (!isConnected) {
        handleError({ message: '尚未连接到服务器！' });
        return;
    }
    
    showLoading('创建房间中...');
    roomId = generateRoomId();
    document.getElementById('room-selection').style.display = 'none';
    document.getElementById('room-info').style.display = 'block';
    
    // 发送加入房间请求
    ws.send(JSON.stringify({
        type: 'joinRoom',
        roomId: roomId,
        playerName: 'Player'
    }));
    
    setTimeout(() => {
        hideLoading();
    }, 1000);
}

// 改进的加入房间功能
function joinRoom() {
    if (!isConnected) {
        handleError({ message: '尚未连接到服务器！' });
        return;
    }
    
    const inputRoomId = document.getElementById('room-input').value.trim();
    if (!inputRoomId) {
        handleError({ message: '请输入房间ID！' });
        return;
    }
    
    showLoading('加入房间中...');
    roomId = inputRoomId;
    document.getElementById('room-selection').style.display = 'none';
    document.getElementById('room-info').style.display = 'block';
    
    // 发送加入房间请求
    ws.send(JSON.stringify({
        type: 'joinRoom',
        roomId: roomId,
        playerName: 'Player'
    }));
    
    setTimeout(() => {
        hideLoading();
    }, 1000);
}

// 生成随机房间ID
function generateRoomId() {
    return Math.random().toString(36).substring(2, 8);
}

// 处理服务器消息
function handleServerMessage(data) {
    switch (data.type) {
        case 'roomUpdate':
            handleRoomUpdate(data);
            break;
        case 'gameStateUpdate':
            handleGameStateUpdate(data);
            break;
        case 'opponentDisconnected':
            handleOpponentDisconnected(data);
            break;
        case 'error':
            handleError(data);
            break;
        case 'rtc-answer':
            rtcPeer.setRemoteDescription(new RTCSessionDescription(data.answer));
            break;
        case 'startNewRound':
            resolveBattle();
            startNewRound();
            break;
    }
}

// 处理房间更新
function handleRoomUpdate(data) {
    playerRole = data.role;
    // 显示房间ID和状态
    document.getElementById('room-id').textContent = roomId;
    document.getElementById('room-status').textContent = data.status === 'playing' ? '已开始，等待对手操作' : '等待玩家加入...';

    // 显示/隐藏游戏区域
    if (data.status === 'playing') {
        document.getElementById('room-container').style.display = 'none';
        document.getElementById('game-container').style.display = '';
        // 初始化游戏
        initGame();
        // 同步游戏状态
        syncGameState();
    } else {
        document.getElementById('room-container').style.display = '';
        document.getElementById('game-container').style.display = 'none';
    }
}

// 处理游戏状态更新
function handleGameStateUpdate(data) {
    if (data.gameState) {
        gameState = data.gameState;
        startTimer(true);
        updateDisplay();
    }
}

// 处理对手断开连接
function handleOpponentDisconnected(data) {
    handleError(data);
}

// 处理错误
function handleError(data) {
    // 创建一个更美观的错误提示
    const errorDiv = document.createElement('div');
    errorDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(45deg, #ff4444, #cc0000);
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(255, 68, 68, 0.5);
        z-index: 1000;
        animation: slideIn 0.3s ease;
        max-width: 300px;
    `;
    errorDiv.textContent = data.message;
    document.body.appendChild(errorDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        errorDiv.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 300);
    }, 3000);
}

// 改进的成功提示
function showSuccess(message) {
    const successDiv = document.createElement('div');
    successDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(45deg, #44ff44, #00cc00);
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(68, 255, 68, 0.5);
        z-index: 1000;
        animation: slideIn 0.3s ease;
        max-width: 300px;
    `;
    successDiv.textContent = message;
    document.body.appendChild(successDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        successDiv.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.parentNode.removeChild(successDiv);
            }
        }, 300);
    }, 3000);
}

// 改进的复制房间ID功能
function copyRoomId() {
    navigator.clipboard.writeText(roomId).then(() => {
        showSuccess('房间ID已复制到剪贴板！');
    }).catch(err => {
        console.error('复制失败：', err);
        handleError({ message: '复制失败，请手动复制房间ID' });
    });
}

// 改进的分享房间功能
function shareRoom() {
    const url = `${window.location.origin}${window.location.pathname}?room=${roomId}`;
    navigator.clipboard.writeText(url).then(() => {
        showSuccess('房间链接已复制到剪贴板！');
    }).catch(err => {
        console.error('复制失败：', err);
        handleError({ message: '复制失败，请手动复制房间链接' });
    });
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// 在页面加载时初始化
window.onload = () => {
    connectToServer();
    
    // 绑定按钮事件
    document.getElementById('create-room').addEventListener('click', createRoom);
    document.getElementById('join-room').addEventListener('click', joinRoom);
    document.getElementById('copy-room-id').addEventListener('click', copyRoomId);
    document.getElementById('share-room').addEventListener('click', shareRoom);
    // 补充：刷新卡牌与升级按钮
    document.getElementById('refresh-cards').addEventListener('click', refreshCards);
    document.getElementById('upgrade').addEventListener('click', upgrade);
    
    // 检查URL中是否有房间ID
    const urlParams = new URLSearchParams(window.location.search);
    const urlRoomId = urlParams.get('room');
    if (urlRoomId) {
        document.getElementById('room-input').value = urlRoomId;
    }
};

function initGame() {
    // 重置游戏状态
    gameState = {
        player: {
            level: 1,
            gold: 100,
            hand: [],
            battle: [],
            maxHandSize: 6,
            health: 30,
            availableCards: new Array(6).fill(0)
        },
        opponent: {
            level: 1,
            gold: 100,
            hand: [],
            battle: [],
            health: 30,
            availableCards: new Array(6).fill(0)
        },
        timer: 20,
        round: 1,
        isRoundEnd: false
    };

    // 初始化游戏
    refreshCards();
    updateDisplay();
    startTimer();
}

function generateOpponentHand() {
    // 获取所有可用的卡牌ID（count > 0的卡牌）
    const availableCardIds = Object.entries(cardConfig.cards)
        .filter(([_, card]) => card.count > 0)
        .map(([id, _]) => parseInt(id));
    
    // 如果没有可用卡牌，直接返回
    if (availableCardIds.length === 0) {
        return;
    }
    
    // 为对手生成手牌
    gameState.opponent.hand = Array.from({length: 6}, () => {
        const randomIndex = Math.floor(Math.random() * availableCardIds.length);
        const cardId = availableCardIds[randomIndex];
        cardConfig.decreaseCardCount(cardId); // 减少卡牌数量
        return cardId;
    });
}

function refreshCards() {
    if(parseInt(gameState.player.gold) < 2) {
        alert('金币不足！需要2金币刷新卡牌。');
        return;
    }

    // 计算场上（战斗区+手牌区）每种牌的数量
    const cardCounts = {};
    [...gameState.player.battle, ...gameState.player.hand, ...gameState.opponent.battle, ...gameState.opponent.hand].forEach(cardId => {
        cardCounts[cardId] = (cardCounts[cardId] || 0) + 1;
    });

    // 过滤出可用的卡牌（count > 0 且场上数量未达到 count）
    const availableCardIds = Object.entries(cardConfig.cards)
        .filter(([id, card]) => {
            const cardId = parseInt(id);
            const currentCount = cardCounts[cardId] || 0;
            return card.count > 0 && currentCount < card.count;
        })
        .map(([id, _]) => parseInt(id));

    if (availableCardIds.length === 0) {
        alert('没有可用的卡牌了！');
        return;
    }

    gameState.player.gold = parseInt(gameState.player.gold) - 2;
    gameState.player.availableCards = Array.from({length: 6}, () => {
        const randomIndex = Math.floor(Math.random() * availableCardIds.length);
        return availableCardIds[randomIndex];
    });
    updateDisplay();
    syncGameState();
}

function upgrade() {
    // 检查金币是否足够
    if(parseInt(gameState.player.gold) < 5) {
        alert('金币不足！需要5金币升级。');
        return;
    }
    
    gameState.player.gold = parseInt(gameState.player.gold) - 5;
    gameState.player.level++;
    updateDisplay();
    syncGameState();
}

function addToHand(cardId) {
    if (gameState.player.hand.length >= gameState.player.maxHandSize) {
        alert('手牌已满！');
        return;
    }
    const cardInfo = cardConfig.getCardInfo(cardId);
    if (!cardInfo) {
        alert('无效的卡牌！');
        return;
    }
    if (parseInt(gameState.player.gold) < cardInfo.cost) {
        alert(`金币不足！需要${cardInfo.cost}金币购买此卡牌。`);
        return;
    }
    if (cardConfig.decreaseCardCount(cardId)) {
        gameState.player.gold = parseInt(gameState.player.gold) - cardInfo.cost;
        gameState.player.hand.push(cardId);
        // 从自己的 availableCards 中移除
        const idx = gameState.player.availableCards.indexOf(cardId);
        if (idx !== -1) gameState.player.availableCards.splice(idx, 1);
        updateDisplay();
        checkCardMerge();
        syncGameState();
    } else {
        alert('该卡牌已用完！');
    }
}

// 检查并处理卡牌合成
function checkCardMerge() {
    // 合并手牌和出牌区的卡牌
    const allCards = [...gameState.player.hand, ...gameState.player.battle.map(c => typeof c === 'object' ? c.id : c)];
    const cardCounts = {};
    
    // 统计每张卡牌的数量
    allCards.forEach(cardId => {
        cardCounts[cardId] = (cardCounts[cardId] || 0) + 1;
    });
    
    // 检查是否有可以合成的卡牌
    for (const [cardId, count] of Object.entries(cardCounts)) {
        if (count >= 3) {
            // 从手牌和出牌区移除这三张卡
            let removedCount = 0;
            // 先从手牌中移除
            for (let i = gameState.player.hand.length - 1; i >= 0 && removedCount < 3; i--) {
                if (gameState.player.hand[i] === parseInt(cardId)) {
                    gameState.player.hand.splice(i, 1);
                    removedCount++;
                }
            }
            // 再从出牌区移除
            for (let i = gameState.player.battle.length - 1; i >= 0 && removedCount < 3; i--) {
                const c = gameState.player.battle[i];
                const cid = typeof c === 'object' ? c.id : c;
                if (cid === parseInt(cardId)) {
                    gameState.player.battle.splice(i, 1);
                    removedCount++;
                }
            }
            // 创建新的合成卡牌对象
            const mergedCardId = parseInt(cardId);
            const cardInfo = cardConfig.getCardInfo(mergedCardId);
            const mergeCount = (cardInfo.mergeCount || 0) + 1;
            // 将合成卡牌对象 push 进 battle
            gameState.player.battle.push({id: mergedCardId, isMerged: true, mergeCount: mergeCount});
            updateDisplay();
            showMergeEffect(mergedCardId, mergeCount);
            checkCardMerge();
            break;
        }
    }
}

// 改进的卡牌合成效果
function showMergeEffect(cardId, mergeCount) {
    // 尝试多种选择器来找到卡牌元素
    let cardElement = document.querySelector(`[data-card-id="${cardId}"]`);
    if (!cardElement) {
        cardElement = document.querySelector(`#player-battle .card[style*="${cardId}.png"]`);
    }
    if (!cardElement) {
        cardElement = document.querySelector(`#player-battle .card[onclick*="${cardId}"]`);
    }
    
    if (cardElement) {
        // 添加合成动画
        cardElement.classList.add('merged-card');
        cardElement.style.setProperty('--merge-count', mergeCount);
        
        // 创建粒子效果
        createParticleEffect(cardElement);
        
        // 播放合成音效（如果支持）
        playSound('merge');
        
        setTimeout(() => {
            cardElement.classList.remove('merged-card');
        }, 2000);
    }
}

// 创建粒子效果
function createParticleEffect(element) {
    const rect = element.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    for (let i = 0; i < 10; i++) {
        const particle = document.createElement('div');
        particle.style.cssText = `
            position: fixed;
            width: 4px;
            height: 4px;
            background: #ff00ff;
            border-radius: 50%;
            pointer-events: none;
            z-index: 1000;
            left: ${centerX}px;
            top: ${centerY}px;
            animation: particle 1s ease-out forwards;
        `;
        
        const angle = (i / 10) * Math.PI * 2;
        const distance = 50 + Math.random() * 50;
        const endX = centerX + Math.cos(angle) * distance;
        const endY = centerY + Math.sin(angle) * distance;
        
        particle.style.setProperty('--end-x', endX + 'px');
        particle.style.setProperty('--end-y', endY + 'px');
        
        document.body.appendChild(particle);
        
        setTimeout(() => {
            if (particle.parentNode) {
                particle.parentNode.removeChild(particle);
            }
        }, 1000);
    }
}

// 播放音效（如果支持）
function playSound(type) {
    // 这里可以添加音效播放逻辑
    // 目前只是占位符
    console.log(`播放音效: ${type}`);
}

function playCard(cardId) {
    if (gameState.isRoundEnd) {
        alert('回合已结束！');
        return;
    }
    const index = gameState.player.hand.indexOf(cardId);
    if (index === -1) {
        console.error('找不到要出的卡牌');
        return;
    }
    if (gameState.player.battle.length >= gameState.player.level) {
        alert(`战场已满！当前等级${gameState.player.level}，最多只能放置${gameState.player.level}张卡牌`);
        return;
    }
    const playedCard = gameState.player.hand.splice(index, 1)[0];
    // 如果是合成卡牌，应该是对象
    if (typeof playedCard === 'object') {
        gameState.player.battle.push(playedCard);
    } else {
        gameState.player.battle.push(playedCard);
    }
    checkCardMerge();
    updateDisplay();
    syncGameState();
    if (gameState.timer <= 0) {
        endRound();
    }
}

function endRound() {
    gameState.isRoundEnd = true;
    clearInterval(timerInterval);
    
    // 添加回合结束的视觉效果
    const gameContainer = document.getElementById('game-container');
    gameContainer.style.animation = 'roundEnd 0.5s ease';
    
    setTimeout(() => {
        gameContainer.style.animation = '';
    }, 500);
    
    // 发送回合结束消息
    ws.send(JSON.stringify({
        type: 'endRound',
        roomId: roomId
    }));
    
    // 同步游戏状态
    syncGameState();
    
    // 等待对手完成回合
    setTimeout(() => {
        resolveBattle();
        startNewRound();
    }, 2000);
}

function startNewRound() {
    gameState.round++;
    gameState.timer = 20;
    gameState.isRoundEnd = false;
    
    gameState.player.gold = parseInt(gameState.player.gold) + 2;
    // 自动刷新一次卡牌
    refreshCards();
    
    // 重新开始计时器
    startTimer();
    
    // 更新显示
    updateDisplay();
    syncGameState();
}

function performOpponentTurn() {
    // 对手AI逻辑
    if (gameState.opponent.hand.length > 0 && gameState.opponent.battle.length < gameState.opponent.level) {
        const randomCard = gameState.opponent.hand.pop();
        gameState.opponent.battle.push(randomCard);
        updateDisplay();
    }
}

function resolveBattle() {
    // 计算双方战斗力
    const playerPower = calculateBattlePower(gameState.player.battle);
    const opponentPower = calculateBattlePower(gameState.opponent.battle);
    
    // 计算伤害（攻击力减去对方防御力）
    const playerDamage = Math.max(0, playerPower.attack - opponentPower.defense);
    const opponentDamage = Math.max(0, opponentPower.attack - playerPower.defense);
    
    // 应用伤害（修正：玩家受到对手伤害，对手受到玩家伤害）
    gameState.player.health -= opponentDamage;
    gameState.opponent.health -= playerDamage;
    
    // 根据胜负给予金币奖励
    if (playerDamage > opponentDamage) {
        gameState.player.gold = parseInt(gameState.player.gold) + 10; // 胜利获得10金币
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 7; // 失败获得7金币
    } else if (opponentDamage > playerDamage) {
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 10; // 胜利获得10金币
        gameState.player.gold = parseInt(gameState.player.gold) + 7; // 失败获得7金币
    } else {
        // 平局双方都获得7金币
        gameState.player.gold = parseInt(gameState.player.gold) + 7;
        gameState.opponent.gold = parseInt(gameState.opponent.gold) + 7;
    }
    
    // 检查游戏是否结束
    checkGameEnd();

    console.log(`玩家攻击:${playerPower.attack} 防御:${playerPower.defense}`);
    console.log(`对手攻击:${opponentPower.attack} 防御:${opponentPower.defense}`);
}

function calculateBattlePower(battleCards) {
    return battleCards.reduce((total, cardObj) => {
        const cardId = typeof cardObj === 'object' ? cardObj.id : cardObj;
        const cardPower = cardConfig.calculateCardPower(cardId, battleCards);
        return {
            attack: total.attack + cardPower.attack,
            defense: total.defense + cardPower.defense
        };
    }, { attack: 0, defense: 0 });
}

// 改进的游戏结束效果
function checkGameEnd() {
    if (gameState.player.health <= 0) {
        showGameOver('你输了！');
    } else if (gameState.opponent.health <= 0) {
        showGameOver('你赢了！');
    }
}

// 显示游戏结束画面
function showGameOver(message) {
    const gameOverDiv = document.createElement('div');
    gameOverDiv.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        z-index: 2000;
        animation: fadeIn 0.5s ease;
    `;
    
    gameOverDiv.innerHTML = `
        <h1 style="color: #00f7ff; font-size: 3rem; margin-bottom: 20px; text-shadow: 0 0 20px #00f7ff;">${message}</h1>
        <button onclick="location.reload()" style="
            padding: 15px 30px;
            font-size: 1.2rem;
            background: linear-gradient(45deg, #00f7ff, #0066ff);
            border: none;
            border-radius: 25px;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 0 15px #00f7ff;
        ">重新开始</button>
    `;
    
    document.body.appendChild(gameOverDiv);
}

// 添加更多动画样式
const additionalStyle = document.createElement('style');
additionalStyle.textContent = `
    @keyframes particle {
        to {
            left: var(--end-x);
            top: var(--end-y);
            opacity: 0;
            transform: scale(0);
        }
    }
    
    @keyframes roundEnd {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.05);
        }
        100% {
            transform: scale(1);
        }
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
        }
        to {
            opacity: 1;
        }
    }
`;
document.head.appendChild(additionalStyle);

function getBattleBonds(battleCards) {
    const bondToCardTypeSet = {};
    battleCards.forEach(cardObj => {
        const cardId = typeof cardObj === 'object' ? cardObj.id : cardObj;
        const card = cardConfig.getCardInfo(cardId);
        if (!card) return;
        [card.bond1, card.bond2].forEach(bond => {
            if (!bond) return;
            if (!bondToCardTypeSet[bond]) bondToCardTypeSet[bond] = new Set();
            bondToCardTypeSet[bond].add(cardId); // 只记录不同卡牌类型
        });
    });
    // 只显示场上有2种及以上不同卡牌类型的羁绊
    return Object.entries(bondToCardTypeSet)
        .map(([bond, set]) => [bond, set.size])
        .filter(([bond, size]) => size >= 2);
}

function renderBonds(bonds, containerId) {
    const container = document.getElementById(containerId);
    container.innerHTML = '';
    if (bonds.length === 0) {
        container.style.display = 'none';
        return;
    }
    container.style.display = 'flex';
    bonds.forEach(([bond, count]) => {
        const item = document.createElement('span');
        item.className = 'bond-item';
        item.textContent = `${bond} ×${count}`;
        container.appendChild(item);
    });
}

function sellCard(cardObj, area) {
    // cardObj 可能是数字或对象
    const cardId = typeof cardObj === 'object' ? cardObj.id : cardObj;
    ws.send(JSON.stringify({
        type: 'sellCard',
        roomId: roomId,
        cardId: cardId,
        area: area,
        isMerged: typeof cardObj === 'object' && cardObj.isMerged
    }));
}

function updateDisplay() {
    // 更新玩家信息
    document.getElementById('player-level').textContent = gameState.player.level;
    document.getElementById('player-gold').textContent = Math.max(0, parseInt(gameState.player.gold) || 0);
    document.getElementById('player-health').textContent = gameState.player.health;
    
    // 更新对手信息
    document.getElementById('opponent-level').textContent = gameState.opponent.level;
    document.getElementById('opponent-gold').textContent = Math.max(0, parseInt(gameState.opponent.gold) || 0);
    document.getElementById('opponent-health').textContent = gameState.opponent.health;
    
    // 更新回合数显示
    document.getElementById('round').textContent = gameState.round;
    document.getElementById('timer').textContent = gameState.timer;
    
    // 清空所有区域
    document.getElementById('player-hand').innerHTML = '';
    document.getElementById('opponent-hand').innerHTML = '';
    document.getElementById('player-battle').innerHTML = '';
    document.getElementById('opponent-battle').innerHTML = '';
    document.getElementById('available-cards').innerHTML = '';

    // 渲染玩家手牌
    gameState.player.hand.forEach(cardId => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.setAttribute('data-card-id', cardId);
        cardElement.onclick = () => playCard(cardId);
        cardElement.oncontextmenu = (e) => {
            e.preventDefault();
            sellCard(cardId, 'hand');
        };
        document.getElementById('player-hand').appendChild(cardElement);
    });

    // 渲染对手手牌（正面展示）
    gameState.opponent.hand.forEach(cardId => {
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.setAttribute('data-card-id', cardId);
        document.getElementById('opponent-hand').appendChild(cardElement);
    });

    // 渲染玩家战场
    gameState.player.battle.forEach(cardObj => {
        const cardId = typeof cardObj === 'object' ? cardObj.id : cardObj;
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.setAttribute('data-card-id', cardId);
        // 检查是否为合成卡牌
        const isMerged = typeof cardObj === 'object' ? cardObj.isMerged : false;
        const mergeCount = typeof cardObj === 'object' ? cardObj.mergeCount : 0;
        if (isMerged) {
            cardElement.classList.add('merged-card');
            cardElement.style.setProperty('--merge-count', mergeCount);
        }
        cardElement.oncontextmenu = (e) => {
            e.preventDefault();
            sellCard(cardObj, 'battle');
        };
        document.getElementById('player-battle').appendChild(cardElement);
    });

    // 渲染对手战场
    gameState.opponent.battle.forEach(cardObj => {
        const cardId = typeof cardObj === 'object' ? cardObj.id : cardObj;
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.setAttribute('data-card-id', cardId);
        const isMerged = typeof cardObj === 'object' ? cardObj.isMerged : false;
        const mergeCount = typeof cardObj === 'object' ? cardObj.mergeCount : 0;
        if (isMerged) {
            cardElement.classList.add('merged-card');
            cardElement.style.setProperty('--merge-count', mergeCount);
        }
        document.getElementById('opponent-battle').appendChild(cardElement);
    });

    // 渲染自己的可用卡牌
    gameState.player.availableCards.forEach(cardId => {
        if (cardId === 0) return;
        const cardElement = document.createElement('div');
        cardElement.className = 'card';
        cardElement.style.backgroundImage = `url(card/${cardId}.png)`;
        cardElement.setAttribute('data-card-id', cardId);
        cardElement.onclick = () => addToHand(cardId);
        document.getElementById('available-cards').appendChild(cardElement);
    });

    // 更新羁绊显示
    const playerBonds = getBattleBonds(gameState.player.battle);
    const opponentBonds = getBattleBonds(gameState.opponent.battle);
    renderBonds(playerBonds, 'player-bonds');
    renderBonds(opponentBonds, 'opponent-bonds');
}

function startTimer(fromSync = false) {
    if (timerInterval) {
        clearInterval(timerInterval);
    }
    // 只有本地操作才重设 timer
    if (!fromSync) {
        gameState.timer = 20;
    }
    document.getElementById('timer').textContent = gameState.timer;

    const startTime = Date.now();
    const initialTimer = gameState.timer;

    timerInterval = setInterval(() => {
        let elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
        let remain = Math.max(0, initialTimer - elapsedSeconds);
        gameState.timer = remain;
        document.getElementById('timer').textContent = remain;
        if (remain === 0 && !gameState.isRoundEnd) {
            clearInterval(timerInterval);
            endRound();
        }
    }, 100);
}

// 同步游戏状态
function syncGameState() {
    if (!roomId) return;
    // 深拷贝 gameState
    const syncState = JSON.parse(JSON.stringify(gameState));
    ws.send(JSON.stringify({
        type: 'syncGameState',
        roomId: roomId,
        gameState: syncState
    }));
}

function setupWebRTC() {
    console.log('[视频] setupWebRTC 被调用');
    try {
        rtcPeer = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' }
            ]
        });
        
        rtcPeer.onicecandidate = (event) => {
            console.log('[视频] onicecandidate:', event.candidate ? '有候选人' : '无候选人');
            if (event.candidate === null) {
                console.log('[视频] 发送 rtc-offer:', rtcPeer.localDescription);
                ws.send(JSON.stringify({ 
                    type: 'rtc-offer', 
                    offer: rtcPeer.localDescription 
                }));
            }
        };

        rtcPeer.oniceconnectionstatechange = () => {
            console.log('[视频] ICE 连接状态变更:', rtcPeer.iceConnectionState);
        };

        rtcPeer.onconnectionstatechange = () => {
            console.log('[视频] 连接状态变更:', rtcPeer.connectionState);
        };

        rtcPeer.ondatachannel = (event) => {
            console.log('[视频] ondatachannel 触发');
            videoChannel = event.channel;
            receivedChunks = [];
            
            videoChannel.onopen = () => {
                console.log('[视频] 数据通道已打开');
            };
            
            videoChannel.onclose = () => {
                console.log('[视频] 数据通道已关闭');
            };
            
            videoChannel.onerror = (error) => {
                console.error('[视频] 数据通道错误:', error);
            };
            
            videoChannel.onmessage = (event) => {
                console.log('[视频] 收到 videoChannel 消息:', event.data === 'END_OF_VIDEO' ? 'END_OF_VIDEO' : '数据块');
                if (event.data === 'END_OF_VIDEO') {
                    console.log('[视频] 收到 END_OF_VIDEO，开始播放');
                    const videoBlob = new Blob(receivedChunks, { type: 'video/mp4' });
                    playReceivedVideo(videoBlob);
                    receivedChunks = [];
                } else {
                    receivedChunks.push(event.data);
                    console.log(`[视频] 收到一个 chunk, 当前共 ${receivedChunks.length} 块`);
                }
            };
        };

        console.log('[视频] 创建数据通道');
        const dataChannel = rtcPeer.createDataChannel('videoChannel', {
            ordered: true,
            maxRetransmits: 3
        });
        
        dataChannel.binaryType = 'arraybuffer';  // 设置为 arraybuffer 以接收二进制数据
        
        dataChannel.onopen = () => {
            console.log('[视频] 本地数据通道已打开，准备接收数据');
        };
        
        dataChannel.onclose = () => {
            console.log('[视频] 本地数据通道已关闭');
        };
        
        dataChannel.onerror = (error) => {
            console.error('[视频] 本地数据通道错误:', error);
        };
        
        dataChannel.onmessage = (event) => {
            console.log('[视频] 本地数据通道收到消息，数据类型:', event.data instanceof ArrayBuffer ? 'ArrayBuffer' : typeof event.data);
            if (event.data === 'END_OF_VIDEO') {
                console.log('[视频] 收到 END_OF_VIDEO，开始播放');
                const videoBlob = new Blob(receivedChunks, { type: 'video/mp4' });
                console.log('[视频] 创建视频 Blob，大小:', videoBlob.size);
                playReceivedVideo(videoBlob);
                receivedChunks = [];
            } else {
                if (event.data instanceof ArrayBuffer) {
                    console.log('[视频] 收到二进制数据块，大小:', event.data.byteLength);
                    receivedChunks.push(new Uint8Array(event.data));
                } else {
                    console.log('[视频] 收到非二进制数据:', event.data);
                }
                console.log(`[视频] 当前已接收 ${receivedChunks.length} 个数据块，总大小:`, 
                    receivedChunks.reduce((total, chunk) => total + chunk.byteLength, 0), '字节');
            }
        };

        console.log('[视频] 创建 offer');
        rtcPeer.createOffer().then(offer => {
            console.log('[视频] createOffer 完成', offer);
            return rtcPeer.setLocalDescription(offer);
        }).catch(error => {
            console.error('[视频] 创建或设置 offer 时出错:', error);
        });
    } catch (error) {
        console.error('[视频] setupWebRTC 出错:', error);
    }
}

function playReceivedVideo(blob) {
    console.log('[视频] playReceivedVideo 被调用, blob size:', blob.size);
    try {
        const videoElement = document.createElement('video');
        const videoUrl = URL.createObjectURL(blob);
        console.log('[视频] 创建视频 URL:', videoUrl);
        
        videoElement.src = videoUrl;
        videoElement.autoplay = true;
        videoElement.controls = true;  // 添加控制条以便调试
        videoElement.style.position = 'fixed';
        videoElement.style.top = '50%';
        videoElement.style.left = '50%';
        videoElement.style.transform = 'translate(-50%, -50%)';
        videoElement.style.zIndex = '9999';
        videoElement.style.background = 'black';
        videoElement.style.width = '80vw';
        videoElement.style.height = 'auto';
        videoElement.style.maxHeight = '80vh';
        
        // 添加错误处理
        videoElement.onerror = (e) => {
            console.error('[视频] videoElement 播放出错:', e);
            if (videoElement.error) {
                console.error('[视频] 错误代码:', videoElement.error.code);
                console.error('[视频] 错误信息:', videoElement.error.message);
            }
            // 清理 URL
            URL.revokeObjectURL(videoUrl);
        };
        
        videoElement.onloadedmetadata = () => {
            console.log('[视频] 视频元数据已加载，时长:', videoElement.duration, '秒');
            console.log('[视频] 视频尺寸:', videoElement.videoWidth, 'x', videoElement.videoHeight);
        };
        
        videoElement.oncanplay = () => {
            console.log('[视频] 视频可以播放');
            videoElement.play().catch(error => {
                console.error('[视频] 播放失败:', error);
            });
        };
        
        videoElement.onplay = () => {
            console.log('[视频] 视频开始播放');
        };
        
        videoElement.onended = () => {
            console.log('[视频] 视频播放结束, 移除 videoElement');
            URL.revokeObjectURL(videoUrl);  // 清理 URL
            document.body.removeChild(videoElement);
            ws.send(JSON.stringify({ type: 'video-played' }));
        };
        
        document.body.appendChild(videoElement);
        console.log('[视频] videoElement 已添加到页面');
    } catch (error) {
        console.error('[视频] playReceivedVideo 出错:', error);
    }
}

// 重置游戏
function resetGame() {
    // 清除计时器
    if (timerInterval) {
        clearInterval(timerInterval);
    }
    
    gameState = {
        player: {
            level: 1,
            gold: 100,
            hand: [],
            battle: [],
            maxHandSize: 6,
            health: 30,
            availableCards: new Array(6).fill(0)
        },
        opponent: {
            level: 1,
            gold: 100,
            hand: [],
            battle: [],
            health: 30,
            availableCards: new Array(6).fill(0)
        },
        timer: 20,
        round: 1,
        isRoundEnd: false
    };
    initGame();
}

// 添加更多动画样式
const loadingStyle = document.createElement('style');
loadingStyle.textContent = `
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    @keyframes fadeOut {
        from {
            opacity: 1;
        }
        to {
            opacity: 0;
        }
    }
`;
document.head.appendChild(loadingStyle);